function [a,ll,iter] = linesearch(parms,d,p2p,Y,H,Q)

a = nan;
ll = nan;

a0 = 0;
[~,f0,g0] = emstep(p2p(parms+a0*d),Y,H,Q);
g0 = g0'*d;

f_start = f0;
g_start = g0;

a1 = 1;

for iter = 1:10
    
    [~,f1,g1] = emstep(p2p(parms+a1*d),Y,H,Q);
    g1 = g1'*d;

    suff_inc = (f1 > (f_start + 0.01*a1*g_start));
    curv_cond = (abs(g1) < (0.9*g_start));

    if suff_inc && curv_cond
        a = a1;
        ll = f1;
        break
    elseif ((sign(a1 - a0)*(g0 - g1)/(abs(g0) + abs(g1)))<1e-5)
        break
    else
        a2 = (a1*g0 - a0*g1)/(g0-g1);
        a0 = a1;
        g0 = g1;
        a1 = a2;
    end

end

end





